<!-- 登录、注册 -->
<template>
  <div>
    <a-modal
      :title="isReg ? '注册用户' : '用户登录'"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @cancel="handleCancel"
      :destroyOnClose="true"
      style="z-index:99999;"
    >
      <template slot="footer">
        <a-button key="back" @click="handleCancel">
          关闭
        </a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="confirmLoading"
          @click="handleOk"
        >
          登录
        </a-button>
      </template>

      <a-form
        id="components-form-demo-normal-login"
        :form="form"
        class="login-form"
        @submit="handleOk"
      >
        <!-- 账号 -->
        <a-form-item>
          <a-input
            v-decorator="[
              'username',
              {
                initialValue: saveUsername,
                rules: [{ required: true, message: '请输入您的账号' }],
              },
            ]"
            placeholder="用户名"
          >
            <a-icon slot="prefix" type="user" style="color: rgba(0,0,0,.25)" />
          </a-input>
        </a-form-item>
        <!-- 密码 -->
        <a-form-item>
          <a-input-password
            v-decorator="[
              'password',
              {
                initialValue: savePasswrod,
                rules: [{ required: true, message: '请输入您的密码' }],
              },
            ]"
            type="password"
            placeholder="密码"
          >
            <a-icon slot="prefix" type="lock" style="color: rgba(0,0,0,.25)" />
          </a-input-password>
        </a-form-item>
        <!-- 验证码 -->
<!--         <a-form-item>
          <a-input
            v-decorator="[
              'verifyCode',
              {
                rules: [{ required: true, message: '请输入验证码' }],
              },
            ]"
            placeholder="验证码"
          >
            <a-icon slot="prefix" type="lock" style="color: rgba(0,0,0,.25)" />
          </a-input>
          <img src="/api/pyUser/verify" alt="">
        </a-form-item> -->
        <!-- 注册时显示 -->
        <template v-if="isReg">
          <!-- 再次输入密码 -->
          <a-form-item>
            <a-input-password
              v-decorator="[
                'repassword',
                {
                  rules: [{ required: true, validator: RepasswordValidator }],
                },
              ]"
              type="password"
              placeholder="确认密码"
            >
              <a-icon
                slot="prefix"
                type="lock"
                style="color: rgba(0,0,0,.25)"
              />
            </a-input-password>
          </a-form-item>
          <!-- 再次输入密码 -->
          <a-form-item>
            <a-input
              v-decorator="[
                'concat',
                {
                  rules: [{ required: false, message: '请输入联系方式' }],
                },
              ]"
              placeholder="联系方式(选填)"
            >
              <a-icon
                slot="prefix"
                type="paper-clip"
                style="color: rgba(0,0,0,.25)"
              />
            </a-input>
          </a-form-item>
          <!-- 用户名 -->
          <a-form-item>
            <a-input
              v-decorator="[
                'name',
                {
                  rules: [{ required: true, message: '请输入名称' }],
                },
              ]"
              placeholder="显示的名称"
            >
              <a-icon
                slot="prefix"
                type="team"
                style="color: rgba(0,0,0,.25)"
              />
            </a-input>
          </a-form-item>
          <!-- 问题 -->
          <a-form-item>
            <a-input
              v-decorator="[
                'question',
                {
                  rules: [
                    { required: true, message: '请输入找回密码时的问题' },
                  ],
                },
              ]"
              placeholder="找回密码时的问题"
            >
              <a-icon
                slot="prefix"
                type="question-circle"
                style="color: rgba(0,0,0,.25)"
              />
            </a-input>
          </a-form-item>
          <!-- 问题答案 -->
          <a-form-item>
            <a-input
              v-decorator="[
                'answer',
                {
                  rules: [{ required: true, message: '请输入问题答案' }],
                },
              ]"
              placeholder="找回密码时的答案"
            >
              <a-icon
                slot="prefix"
                type="profile"
                style="color: rgba(0,0,0,.25)"
              />
            </a-input>
          </a-form-item>
        </template>

        <a-form-item>
          <a-checkbox
            v-decorator="[
              'remember',
              {
                valuePropName: 'checked',
                initialValue: true,
              },
            ]"
          >
            记住我
          </a-checkbox>
          <a class="login-form-forgot">
            忘记密码
          </a>
          <a @click="isReg = !isReg">
            {{ tag }}
          </a>
          <a-button
            v-show="false"
            type="primary"
            html-type="submit"
            class="login-form-button"
          >
            Log in
          </a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';

import { register } from "@/apis/user";
import { saveLoginInfo, dontSaveLogin, getSaveLogin } from "@/utils/auth";
export default {
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    // 这里存放数据
    return {
      visible: this.visible,
      confirmLoading: false,
      form: this.$form.createForm(this, { name: "normal_login" }),
      loading: false,
      isReg: false,
      tag: "点我注册",
      saveUsername: "",
      savePasswrod: "",
    };
  },
  props: {
    show: {
      type: Boolean,
      default: false,
      required: true,
    },
    register: {
      type: Boolean,
      default: false,
      required: true,
    },
  },
  // 监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    show(newValue, oldValue) {
      this.visible = newValue;
    },
    visible(newValue, oldValue) {
      this.$emit("update:show", this.visible);
      if (getSaveLogin()) {
        let data = window.decodeURIComponent(atob(getSaveLogin())).split(",");
        this.saveUsername = data[0];
        this.savePasswrod = data[1];
      }
    },
    register(newValue, oldValue) {
      this.isReg = newValue;
    },
    isReg(newValue, oldValue) {
      this.tag = newValue ? "点我登录" : "点我注册";
    },
  },
  //方法集合
  methods: {
    handleOk(e) {
      this.confirmLoading = true;
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          if (this.isReg) {
            let data = {
              username: values.username,
              password: values.password,
              name: values.name,
              question: values.question,
              answer: values.answer,
              concat: values.concat,
            };
            register(data).then((res) => {
              this.$message.success(res.msg);
            });
          } else {
            let data = {
              username: values.username,
              password: values.password
            };
            this.$store
              .dispatch("user/login", data)
              .then((res) => {
                if (values.remember) {
                  saveLoginInfo(data);
                } else {
                  dontSaveLogin();
                }
                let id = res.id;
                this.visible = false;
                this.confirmLoading = false;
                this.$store.dispatch(
                  "websocket/WEBSOCKET_INIT",
                  "ws://yeziji.xyz/wss/webSocket/" + id
                );
                location.reload();
              })
              .catch(() => {
                this.confirmLoading = false;
              });
          }
        }
        this.confirmLoading = false;
      });
    },
    RepasswordValidator(rule, value, callback) {
      let { password } = this.form.getFieldsValue();
      if (password !== value) callback("确认密码不正确");
      if (value === "") callback("请输入确认密码");
      callback();
    },
    handleCancel(e) {
      this.visible = false;
      this.confirmLoading = false;
      this.$emit("update:show", this.visible);
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="scss" scoped>
//@import url(); 引入公共css类
</style>
